import { readonly, watch } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useInfinite } from '@/compositions/request/infinite'
import { NOTIFY_STATUS, NOTIFY_TYPE } from '@/constant/chat'
import API from '@/http'

export const useSystemNotifyStore = defineStore('systemNotify', () => {
  const {
    dataList: allList,
    loading: allLoading,
    noMore: allNoMore,
    errorMsg: allErrorMsg,
    init: allInit,
    refresh: allRefresh,
    nextPage: allNextPage,
    reset: allReset,
  } = useInfinite({ request: API.Chat.getNotifyList })

  const {
    dataList: commentList,
    loading: commentLoading,
    noMore: commentNoMore,
    errorMsg: commentErrorMsg,
    init: commentInit,
    refresh: commentRefresh,
    nextPage: commentNextPage,
    reset: commentReset,
  } = useInfinite({ request: API.Chat.getNotifyList, params: { type: NOTIFY_TYPE.COMMENT } })

  const {
    dataList: replyList,
    loading: replyLoading,
    noMore: replyNoMore,
    errorMsg: replyErrorMsg,
    init: replyInit,
    refresh: replyRefresh,
    nextPage: replyNextPage,
    reset: replyReset,
  } = useInfinite({ request: API.Chat.getNotifyList, params: { type: NOTIFY_TYPE.REPLY } })

  function notifyRead(notify) {
    if (notify.status === NOTIFY_STATUS.READ) {
      return
    }

    const id = notify.id
    API.Chat.notifyRead({ data: { id } })
      .then(() => {
        const setNotifyRead = (notify) => {
          if (notify.id === id) {
            notify.status = NOTIFY_STATUS.READ
            notify.nums = 0
          }
        }
        allList.value.forEach(setNotifyRead)
        commentList.value.forEach(setNotifyRead)
        replyList.value.forEach(setNotifyRead)
      })
      .catch((e) => console.warn('通知已讀炸了...', e))
  }

  const accountStore = useAccountStore()
  const { isLogin } = storeToRefs(accountStore)
  watch(
    isLogin,
    (v) => {
      if (v) {
        allInit()
        commentInit()
        replyInit()
      } else {
        allReset()
        commentReset()
        replyReset()
      }
    },
    { immediate: true },
  )

  return {
    allList: readonly(allList),
    allLoading,
    allNoMore,
    allErrorMsg,
    allNextPage,

    commentList: readonly(commentList),
    commentLoading,
    commentNoMore,
    commentErrorMsg,
    commentNextPage,

    replyList: readonly(replyList),
    replyLoading,
    replyNoMore,
    replyErrorMsg,
    replyNextPage,

    notifyRead,
  }
})
